package cfs.controller;

import java.sql.Date;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.mybeans.dao.DAOException;
import org.mybeans.form.FormBeanException;
import org.mybeans.form.FormBeanFactory;

import cfs.databean.CFSTransaction;
import cfs.databean.Customer;
import cfs.databean.Fund;
import cfs.formbean.BuyFundFormBean;
import cfs.helper.Helper;
import cfs.helper.TransactionTypes;
import cfs.model.CustomerDAO;
import cfs.model.FundDAO;
import cfs.model.Model;
import cfs.model.TransactionDAO;

public class BuyFundAction extends Action {

	private FormBeanFactory<BuyFundFormBean> formBeanFactory = FormBeanFactory
			.getInstance(BuyFundFormBean.class);

	private FundDAO fundDAO;
	private CustomerDAO customerDAO;
	private TransactionDAO transactionDAO;

	public BuyFundAction(Model model) {
		transactionDAO = model.getTransactionDao();
		fundDAO = model.getFundDao();
		customerDAO = model.getCustomerDao();
	}

	@Override
	public String getName() {
		// TODO Auto-generated method stub
		return "buyFund.do";
	}

	@Override
	public String perform(HttpServletRequest request) {
		HttpSession session = request.getSession();
		List<String> errors = new ArrayList<String>();
		request.setAttribute("errors", errors);

		try {
			BuyFundFormBean form = formBeanFactory.create(request);
			request.setAttribute("form", form);
			Customer user = (Customer) session.getAttribute("user");
			long availablebalance = customerDAO.getAvailableBalance(user
					.getCustomer_id());
			request.setAttribute("availablebalance",
					"$" + Helper.longToDouble2String(availablebalance));

			if (!form.isPresent()) {
				return "BuyFundPage.jsp";
			}

			errors.addAll(form.getValidationErrors());
			if (errors.size() > 0) {
				return "BuyFundPage.jsp";
			}

			Fund fundReturned = fundDAO.lookup(form.getSymbol());
			request.setAttribute("fund", fundReturned);

			if (fundReturned == null) {
				errors.add("Fund not exists,please check symbol you entered.");
			}

			// amount check
			double buyAmount = Double.parseDouble(form.getAmount());
			long amount = Helper.double2ToLong(buyAmount);
			if (availablebalance < amount) {
				errors.add("Insufficent balance,please check your balance");
			}

			if (errors.size() > 0) {
				return "BuyFundPage.jsp";
			}

			// Create Transaction
			CFSTransaction transaction = new CFSTransaction();

			transaction.setCustomer_id(user.getCustomer_id());
			transaction.setAmount(amount);
			transaction.setTransaction_type(TransactionTypes.BUY_FUND);
			transaction.setFund_id(fundReturned.getFund_id());
			transaction.setRequest_date(new Date((new java.util.Date().getTime())));
			transaction.setStatus(Helper.PENDING_STATUS);

			transaction = transactionDAO.create(transaction);

			// UPDATA CUSTOMER
			customerDAO.updateAvailableBalance(user.getCustomer_id(),
					availablebalance - amount);

			availablebalance = customerDAO.getAvailableBalance(user
					.getCustomer_id());
			request.setAttribute("availablebalance",
					"$" + Helper.longToDouble2String(availablebalance));


			request.setAttribute("successStatement", form.getSymbol() + " has been purchased ");
			return "customerTransaction.do";

		} catch (DAOException e) {
			errors.add(e.getMessage());
			errors.add("Please check if this fund's information correct,we are unable to buy fund for you at this time");

		} catch (FormBeanException e) {
			errors.add("Please check your informaiton entered in this page");

		} catch (NumberFormatException e) {
			errors.add("Please input a correct number format");

		} catch (Exception e) {
			errors.add("ERROR");
		}
		return "BuyFundPage.jsp";
	}
}
